package com.gzwanchuang.lszg.module.mine;

/**
 * 文件名 : BindBankCardActivity
 * 创建者 : MangoWang
 * 创建日期 : 2019/11/27 18:11
 * 微信 : MangoWaWang
 * 邮箱 : 763482205@qq.comma
 * 描述 : TODO
 */

import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.fragment.app.DialogFragment;


import com.gzwanchuang.lszg.R;
import com.gzwanchuang.lszg.base.BaseActivity;
import com.gzwanchuang.lszg.help.UserHelper;
import com.gzwanchuang.lszg.net.Apis;
import com.gzwanchuang.lszg.net.NetworkManager;
import com.gzwanchuang.lszg.net.interfaces.OnRequestCallBack;
import com.gzwanchuang.lszg.proto.Connect;
import com.gzwanchuang.lszg.proto.MemberBank;
import com.gzwanchuang.lszg.utils.StatusBarUtil;

import butterknife.BindView;
import butterknife.ButterKnife;
import kale.ui.view.dialog.EasyDialog;

public class BindBankCardActivity extends BaseActivity {


    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.back_iv)
    ImageView backIv;
    @BindView(R.id.name_et)
    EditText nameEt;
    @BindView(R.id.card_number_et)
    EditText cardNumberEt;
    @BindView(R.id.phone_et)
    EditText phoneEt;
    @BindView(R.id.mobile_code_et)
    EditText mobileCodeEt;
    @BindView(R.id.get_code_tv)
    TextView getCodeTv;
    @BindView(R.id.btn_add_card)
    Button btnAddCard;

    private String mPhone;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind_bank_card);
        ButterKnife.bind(this);
        StatusBarUtil.setStatusBarLightMode(this, Color.parseColor("#ffffff"), true);
        initListener();
        nameEt.setText(UserHelper.getUser().getTruename());
        tvTitle.setText("换绑新的银行卡");
    }

    private void initListener() {
        backIv.setOnClickListener(view -> {
            EasyDialog.Builder builder = EasyDialog.builder(this); // 建立builder对象
            builder.setTitle("提示")
                    .setMessage("是否放弃换绑银行卡")
                    .setOnCancelListener(dialogInterface -> {

                    })
                    .setOnDismissListener(dialogInterface -> {

                    })
                    // 设置下方的三个按钮
                    .setPositiveButton("确定", (dialog, which) -> {
                        finish();
                    })
                    .setNegativeButton("取消", (dialog, which) -> dialog.dismiss())
                    .setCancelable(true); // 点击空白处可以关闭

            DialogFragment easyDialog = builder.build();

// 用showAllowingStateLoss()弹出
            easyDialog.show(getSupportFragmentManager(), "");
        });
        getCodeTv.setOnClickListener(view -> {
            getCode();
        });
        btnAddCard.setOnClickListener(view -> {
            sumbit();
        });
        cardNumberEt.addTextChangedListener(new PhoneNumberTextWatcher(cardNumberEt));

    }


    /**
     * 获取验证码
     */
    private void getCode() {
        mPhone = phoneEt.getText().toString();
        if (TextUtils.isEmpty(mPhone)) {
            showToast("请输入手机号码");
            return;
        }
        Connect.captcha.Builder builder = Connect.captcha.newBuilder();
        builder.setPhone(mPhone);
        builder.setType("5");
        Connect.captcha data = builder.build();
        showProgress();
        NetworkManager.INSTANCE.post(Apis.getMobileCode, data.toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) {
                hideProgress();
            }

            @Override
            public void onError(int code, String errorMessage) {
                hideProgress();
                showToast(errorMessage);
                if (code == 200) {
                    countDownReSend(getCodeTv, 60);
                }
            }
        });
    }
//
    private void sumbit() {
        String account = nameEt.getText().toString();
        if (TextUtils.isEmpty(account)) {
            showToast("请输入持卡人姓名");
            return;
        }
        String CardNumber = cardNumberEt.getText().toString().trim();
        if (TextUtils.isEmpty(CardNumber)) {
            showToast("请输入银行卡号");
            return;
        }


        String phone = phoneEt.getText().toString();
        if (TextUtils.isEmpty(phone)) {
            showToast("请输入预留手机");
            return;
        }

        String MobileCode = mobileCodeEt.getText().toString();
        if (TextUtils.isEmpty(MobileCode)) {
            showToast("请输入验证码");
            return;
        }
        MemberBank.bank.Builder builder = MemberBank.bank.newBuilder();
        builder.setBankCard(CardNumber)
                .setUserName(account)
                .setPhone(phone).
                setCaptcha(MobileCode);
        showProgress();
        NetworkManager.INSTANCE.post(Apis.bank_card_add, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) {

            }

            @Override
            public void onError(int code, String errorMessage) {
                hideProgress();
                if (code == 200) {
                    showToast(errorMessage);
                    finish();
                } else {
                    showHintDialog(errorMessage);
                }
            }
        });
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {

            EasyDialog.Builder builder = EasyDialog.builder(this); // 建立builder对象
            builder.setTitle("提示")
                    .setMessage("是否放弃绑定银行卡")
                    .setOnCancelListener(dialogInterface -> {

                    })
                    .setOnDismissListener(dialogInterface -> {

                    })
                    // 设置下方的三个按钮
                    .setPositiveButton("确定", (dialog, which) -> {
                       finish();
                    })
                    .setNegativeButton("取消", (dialog, which) -> dialog.dismiss())
                    .setCancelable(true); // 点击空白处可以关闭

            DialogFragment easyDialog = builder.build();

// 用showAllowingStateLoss()弹出
            easyDialog.show(getSupportFragmentManager(), "");
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }



    public class PhoneNumberTextWatcher implements TextWatcher {
        EditText editText;
        int lastContentLength = 0;
        boolean isDelete = false;
        public PhoneNumberTextWatcher(EditText editText) {
            this.editText = editText;
        }
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            StringBuffer sb = new StringBuffer(s);
            //是否为输入状态
            isDelete = s.length() > lastContentLength ? false : true;
            //输入是第4，第9位，这时需要插入空格
            if(!isDelete&& (s.length() == 5||s.length() == 10||s.length() == 15)){
                if(s.length() == 5) {
                    sb.insert(4, " ");
                }else if (s.length() == 10){
                    sb.insert(9, " ");
                }else if (s.length() == 15){
                    sb.insert(14, " ");
                }
                setContent(sb);
            }
            //删除的位置到4，9时，剔除空格
            if (isDelete && (s.length() == 5||s.length() == 10||s.length() == 15)) {
                sb.deleteCharAt(sb.length() - 1);
                setContent(sb);
            }
            lastContentLength = sb.length();
        }
        @Override
        public void afterTextChanged(Editable s) {
        }
        /**
         * 添加或删除空格EditText的设置
         *
         * @param sb
         */
        private void setContent(StringBuffer sb) {
            editText.setText(sb.toString());
            //移动光标到最后面
            editText.setSelection(sb.length());
        }
    }
}
